package com.example.myapplication

import android.app.Application
import android.content.Context
import android.os.BatteryManager
import android.util.Log
import android.widget.Toast
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.FlutterEngineCache
import io.flutter.embedding.engine.dart.DartExecutor
import io.flutter.plugin.common.MethodChannel

class MyApplication : Application() {
    lateinit var flutterEngine: FlutterEngine

    override fun onCreate() {
        super.onCreate()
        flutterEngine = FlutterEngine(this)
        flutterEngine.dartExecutor.executeDartEntrypoint(
            DartExecutor.DartEntrypoint.createDefault()
        )
        setupMethodChannel(flutterEngine)
        FlutterEngineCache.getInstance().put("my_engine_id", flutterEngine)
    }

    private fun setupMethodChannel(flutterEngine: FlutterEngine) {
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "samples.flutter.dev/battery")
            .setMethodCallHandler { call, result ->
                when (call.method) {
                    "getBatteryLevel" -> {
                        Log.e("MyApplication", "getBatteryLevel-监听")
                        result.success(getBatteryLevel())
                    }
                    "showToast" -> {
                        Log.e("MyApplication", "showToast-监听")
                        val message = call.arguments as? String ?: "默认消息"
                        showToast(message)
                        result.success(null)
                    }
                    "getUserInfo" -> {
                        Log.e("MyApplication", "getUserInfo-监听")
                        val userInfo = hashMapOf(
                            "name" to "John",
                            "age" to 30,
                            "isPremium" to true
                        )
                        Log.e("MyApplication", "getUserInfo-返回数据: $userInfo")
                        showToast("getUserInfo-返回数据: $userInfo")
                        result.success(userInfo)
                    }
                    else -> result.notImplemented()
                }
            }
    }

    private fun getBatteryLevel(): Int {
        val batteryManager = getSystemService(Context.BATTERY_SERVICE) as BatteryManager
        return batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
    }

    private fun showToast(message: String) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
    }
}